
;
//var RecycleSystem = function() {
cmedit.RecycleSystem = (function($, window, document) {
    var thisContext;
    var resourceType="1";
    var privilegeInfo = JSON.parse(window.sessionStorage.getItem(cmedit.global.privilegeInfo));
    var leftType="1";
    var mainIsDeleted=0;
    var tabActivelist=[];
    var loadTimeout = cmedit.global.loadTimeout;
    var privilegeIds=window.sessionStorage.getItem(cmedit.global.privilegeIds);
    var userColumnIds=window.sessionStorage.getItem(cmedit.global.userColumnIds);
    var allColumnIds = window.sessionStorage.getItem(cmedit.global.allColumnIds);
    var columnInfo = JSON.parse(window.sessionStorage.getItem(cmedit.global.columnInfo));
    var allColumnInfo = JSON.parse(window.sessionStorage.getItem(cmedit.global.allColumnInfo));
    var bigColumnId = window.sessionStorage.getItem(cmedit.global.bigColumnId);
    var creImportTaskFlag = window.sessionStorage.getItem(cmedit.global.creImportTaskFlag);
	var tenantId = window.localStorage.getItem("tenantId");
	var userId = window.localStorage.getItem("userId");
	var token = window.localStorage.getItem("token");
    var checkAllStatus = false;// (版本对比模态框)全选状态
    var topUtil;  //顶层工具类
    var imgList={};
    var selectIds=[];
    var selectColumnIds=[];
    var listTotalCount;
    var listPageSize;
    var orderName='';
    var pageNow;
    var orderDirection='';
	var RecycleSystemClass = function(){
	    	
	    }
	RecycleSystemClass.prototype = {
    	constructor : RecycleSystemClass,
    		
        initHeader : function() {
        	thisContext = this;
        	topUtil = window.parent.cmedit.global;
			thisContext.init();
           
        },
        /**
         * 真正的初始化方法
         */
        init : function(){
        	thisContext.initViewStyle();
        	thisContext.initColumn();
        	thisContext.initData();
        	thisContext.initEvent();
        },
        refresh : function(){
        	$('#manuscripyTable').bootstrapTable('refresh');
        },
        /**
         * 初始化页面视图
         */
        initViewStyle : function() {
        	
        	/*$('.re-content').css('height',$(document).height()-110+'px');*/
            $('.re_contleft .slimScrollDiv').css('height',$(document).height()-136+'px');
            $('.tab-content').css('height',$('.portlet-body').innerHeight()-40+'px');
//            $('.line-body').css('height',$('.cont_container').innerHeight()-203+'px');
//
//            /*修改滚动条样式*/
//            var linescroll_height=$('.line-body').height();
//            thisContext.scrollType('.line-body',linescroll_height);
            
            var versionscroll_height=$('.versionContainer').css('maxHeight');
            thisContext.scrollType('.versionContainer',versionscroll_height);
            
            $('#startTime').datepicker({clearBtn: true,format: 'yyyy-mm-dd',autoclose: true});
            $('#endTime').datepicker({clearBtn: true,format: 'yyyy-mm-dd',autoclose: true});
        },
        /**
         * 时间排序
         */
        orderby : function(id,orderDirectionName){
        	orderName=id;
        	orderDirection=orderDirectionName;
        	thisContext.initData(pageNow);
        },
        /**
         * 初始化数据
         */
        initData : function(_currentPage,_pageSize) {
        	window.parent.cmedit.ManuscriptSystem.updatePortalStorageExpireTime();
//        	$('#allSelected').prop('checked',false);
//        	$('#manuscripyBody').html(cmedit.global.loaderHtml);
        	var $tableid = $('#manuscripyTable');
        	var url = cmedit.global.cmsPath+"ManuscriptMainController/getRecycleManuscriptByPage";
        	var gc = "";
        	//判断权限中是否有终审浏览权限，如果有，则显示终审浏览
            if(privilegeIds.indexOf(cmedit.global.privilegeFinalcensor) != -1){
            	gc = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditFinal));
            	resourceType = '0';
        	}else{
        		gc = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditRecycle));
        	}
        	var cmeditList = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditTypes));
        	var hasCheckbox = true;
        	if($('#searchContent').val()!=null && $('#searchContent').val()!=''){
        		var title=$('#searchContent').val();
        	}else{
        		var title='';
        	}
//          if($('#endTime').val()!=null && $('#endTime').val()!=''){
            if(($('#endTime').val()!=null && $('#endTime').val()!='') || ($('#startTime').val()!=null && $('#startTime').val()!='')){
        		var dateranges=$("#startTime").val()+" - "+$("#endTime").val();
        	}else{
        		var dateranges='';
        	}
            var currentPage = _currentPage ? _currentPage : 1;
            var pageSize =_pageSize ? _pageSize : 10;
        	var states=$(".container_buttons button[class*='active']").attr("states");
        	resourceType=resourceType?resourceType:'1';
        	//判断权限中是否有终审浏览权限，如果有，则显示终审浏览
        	/*for(var i = 0;i<privilegeInfo.length;i++ ){
				if(privilegeInfo[i].id == "PID_CMEDIT_FINALCENSOR"){
					resourceType = '0';
				}
			}*/
        	mainIsDeleted=mainIsDeleted?mainIsDeleted:'0';
        	var columnId=$("#preReportColumn").val()!=""?$("#preReportColumn").val():"";
        	var queryParams={
        			resourceType:resourceType,
            		mainIsDeleted:mainIsDeleted,
            		userColumnIds:userColumnIds,
            		mainHeader:title,
            		mainStatus:states,
            		columnId:columnId,
            		dateranges:dateranges,
            		mainType:0, //0:网页稿件类型
                    currentPage:currentPage,
                    pageSize:pageSize
            	};
        	var tableParams = {
        			$tableid: $tableid,
        			url: url,
	        		gc: gc,
	        		hasCheckbox: hasCheckbox,
	        		tenantId: tenantId,
	        		userId: userId, 
	        		token: token,
	        		cmeditList: cmeditList,
	        		resourceType : "manuRecycle",
	        		callBackLoadData:function(start,size){
	                	thisContext.initData(start,size);
	                }

            };
            console.log('tableParams:'+tableParams);
            TableInit(tableParams, queryParams);
        },
        /**
         * 初始化分页
         */
        initPage : function(totalPage){
        	$("#pagination").whjPaging({
                /*pageSizeOpt: [
                    {'value': 5, 'text': '5/page', 'selected': true},
                    {'value': 10, 'text': '10/page'},
                    {'value': 15, 'text': '15/page'},
                    {'value': 20, 'text': '20/page'}
                ],*/
                totalPage: totalPage,
                showPageNum: 4,
                firstPage: '<i class="iconfont icon-diyiye"></i>',
                previousPage: '<i class="iconfont icon-shangyiye"></i>',
                nextPage: '<i class="iconfont icon-xiayiye"></i>',
                lastPage: '<i class="iconfont icon-weiye"></i>',
                skip: 'skip',
                confirm: 'go',
                refresh: 'refresh',
                totalPageText: 'the total {} pages',
                isShowFL: true,
                isShowPageSizeOpt: false,
                isShowSkip: false,
                isShowRefresh: false,
                isShowTotalPage: false,
                isResetPage: true,
                callBack: function (currPage, pageSize) {
                	pageNow=currPage;
                    thisContext.initData(currPage);
                }
            });
        },
        /**
         * 初始化事件
         */
        initEvent : function() {
        	$('.editButton').on('mouseover',function(){
        		$('.topNews').show();
        	});
        	$('.editButton').on('mouseout',function(){
        		$('.topNews').on('mouseover',function(){
            		$('.topNews').show();
            	});
        		$('.topNews').on('mouseout',function(){
            		$('.topNews').hide();
            	});
        	});
        	
            $('.nav-link').on('click',function () {
                $('.nav-link').removeClass('nav_active');
                $(this).addClass('nav_active');
            });
            
            $('.container_buttons button').on('click',function () {
                $(this).addClass('active').siblings().removeClass('active');
                thisContext.initData();
            });
            
            $('.manu_copy').on('click',function(){
                var tipHeight=$(window).height()-$(this).offset().top;
                if(tipHeight<232){
                    $(this).next().removeClass('dropdown-menutop');
                    $(this).next().addClass('dropdown-menubot');
                }
            });
            
            /**
             * 审核意见改变时，根据审核意见隐藏或者显示指定审核人
             */
            $("input[name='censorType']").on('change',function(){
            	var censorResultType = $("input[name='censorType']:checked").val();
            	if(censorResultType == "3"){
            		$('.checkPeople').hide();
            	}else if(censorResultType == "2"){
            		$('.checkPeople').show();
            	}
            });
            
            $(".modalClose").on('click',function(){
            	thisContext.initModel();
            });
            
           
		  //刷新列表
			$('.manu_refresh').on('click',function(){
				$("#preReportColumn").val('');
				$('#searchContent').val('');
				$("#preReportColumn").selectpicker('refresh');
				$(".container_buttons button[states='']").addClass('active').siblings().removeClass('active');

				//thisContext.initData();
				$('.date-picker input').val('').datepicker('clearDates');
			});
			/*$('#confirmCensor').on('click',function(){
				var son = window.top.document.getElementsByName('manuscriptIframe')[0].contentWindow;
				son.cmedit.EditSystem.censorManuscript();
			});*/
			
        },
        /**
         * 全选
         */
        allfileSelected : function(){
            if($('#allSelected').prop('checked')){
                $('.select-check').prop('checked',true);
                $('.list_check').addClass('list_checked');
                $('.res-one').addClass('ulChecked');
                selectIds=[];
                for(var i=0;i<$('#manuscripyBody .list_checked').length;i++){
                	selectIds.push($('#manuscripyBody .listone_check').eq(i).attr('id'));
                }
            }else{
                $('.select-check').prop('checked',false);
                $('.list_check').removeClass('list_checked');
                $('.res-one').removeClass('ulChecked');
                selectIds=[];
            }
        },
        /**
         * 选择框点击事件
         */
        listOneCheckClick : function(obj,id,columnId){
        	/*setTimeout(function(){*/
	            if(!$(obj).prev().prop('checked')){
	                $(obj).addClass('list_checked');
	                selectIds.push(id);
	                if(listTotalCount >= listPageSize){
	                	if($('.list_checked').length >= listPageSize){
	                        $('#allSelected').prop('checked',true);
	                    }
	                }else{
	                	if($('#manuscripyBody .list_checked').length == listTotalCount){
	                    	$('#allSelected').prop('checked',true);
	                    }
	                }
	            }else{
	                $(obj).removeClass('list_checked');
	                selectIds.splice($.inArray(id,selectIds),1);
	                $('#allSelected').prop('checked',false);
	                $('#allSelected').next().removeClass('list_checked');
	            }
        	/*},200);*/
        },
        /**
         * 锁定/解锁稿件
         */
        lockManuscript : function(mainGuid,lockOrUnlock){
        	var flag = false;
        	var postData = {
    			mainGuid :mainGuid,
    			privilegeIds : "",
    			lockOrUnlock : lockOrUnlock,
    		};
        	cmedit.global.ajaxRequest({
        		type : 'POST',
        		url : cmedit.global.cmsPath + 'ManuscriptMainController/lockOrUnlockManuscript',
        		data : postData,
        		dataType : 'json',
        		async: false,
        		success : function(data) {
        			if (data.status) {
        				flag = true;
        			} else {
        				alert(data.msg);
        				flag = false;
        			}
        		}
        	});
        	return flag;
        },
        /**
         * 重置tab宽度
         */
        resizeTab : function(){
        	var addTabnums=$(".nav-tabs li").length;
        	var maxWidth=($('.nav-tabs').width()-100)/addTabnums-52;
        	console.log(maxWidth);
        	$('.nav-tabs li span').css('maxWidth',maxWidth);
        },
        /**
         *滚动条样式
         */
        scrollType : function(scrollId,scrollHeight) {
            $(scrollId).slimScroll({
                height: scrollHeight,//可滚动区域高度
                size: '5px',//组件宽度
                color: '#999',//滚动条颜色
                railOpacity: .3,//滚动条透明度
                disableFadeOut: true,//鼠标经过可滚动区域时显示组件，离开时隐藏组件
                wheelStep: 20, //滚轮滚动量
                alwaysVisible: true,//始终显示组件
                borderRadius: '7px' //滚动条圆角
            });
        },
        
        /**
         * 还原稿件
         */
        restoreManuscript : function() {
        	var choosenList =$('#manuscripyTable').bootstrapTable('getSelections');
        	if (choosenList.length == 0) {
        		$.notify("请先选择记录！");
				$('.manuLoader').hide();
				return false;
        	}
        	var selectManuIds=[];
        	for(var i=0; i <choosenList.length;i++){
        		selectManuIds.push(choosenList[i].mainGuid);
    		}
        	window.parent.cmedit.ManuscriptSystem.restoreManuscript(selectManuIds);
        },
        
        /**
         * 彻底删除稿件 无法还原
         */
        deleteManuscriptReal : function() {
        	var choosenList =$('#manuscripyTable').bootstrapTable('getSelections');
        	if (choosenList.length == 0) {
        		$.notify("请先选择记录！");
				$('.manuLoader').hide();
				return false;
        	}
        	var selectManuIds=[];
        	for(var i=0; i <choosenList.length;i++){
        		selectManuIds.push(choosenList[i].mainGuid);
    		}
        	window.parent.cmedit.ManuscriptSystem.deleteManuscriptReal(selectManuIds);
        },
        /**
         * 清空回收站
         */
        clearRecycleManuscript : function() {
        	var mainType = '1'; //1：网页稿件
        	window.parent.cmedit.ManuscriptSystem.clearRecycleManuscript(mainType);
        },

        /**
         * 初始化栏目
         */
        initColumn : function(){
        	//判断该成员是否属于大采访部，如果是，则可以显示所有的栏目
        	if(userColumnIds.indexOf(bigColumnId) > 0){
        		for(var i = 0;i < allColumnInfo.length; i++){
            		$("#preReportColumn").append('<option value="'+allColumnInfo[i].id+'">'+allColumnInfo[i].name+'</option>');
            	}
        	}else{
        		for(var i = 0;i < columnInfo.length; i++){
            		$("#preReportColumn").append('<option value="'+columnInfo[i].id+'">'+columnInfo[i].name+'</option>');
            	}
        	}
        	$("#preReportColumn").selectpicker('refresh');
        },
        
        /**
         * 重置页签数组
         */
        tablistChange : function(addGuid){
        	tabActivelist.splice($.inArray('new',tabActivelist),1);
        	tabActivelist.push(addGuid);
        },
        //更新门户redis存储信息过期时间
		updatePortalStorageExpireTime : function() {
			if(cmedit.global.isPublish){
				$.updateStorageExpireTime();
			}
        },
        
        /**
         * 浏览器页签关闭时，全部解锁功能
         */
        unLockAll : function(){
        	/*console.log(tabActivelist);
        	for(var i=0;i<tabActivelist.length;i++){
        		if(tabActivelist[i] != 'manuSend' && tabActivelist[i] != 'manuTask' && tabActivelist[i] != 'manuDownload'){
                	thisContext.lockManuscript(tabActivelist[i],false);
                }
        	}*/
        	topUtil.ajaxRequest({
				type: "post",
				async: false,
				dataType: "json",
				url: cmedit.global.cmsPath+"ManuscriptMainController/unlockManuscriptByUserId",
				success: function(data) {
					if(data.status) {
						return;
					}else{
						return;
					}
				}
			});
        	
        },
        empty : null
    };
	return new RecycleSystemClass();
})(jQuery, window, document);
//}();
$(cmedit.RecycleSystem.initHeader(),
/**
 * 监听资源库信息
 */
window.addEventListener('message',function(e){
	var CFBExternalUrl = window.sessionStorage.getItem("CFBExternalUrl");
	/*var HJTaskbaseurl = $("#HJTaskbaseurl").val();
    if(HJTaskbaseurl.indexOf(e.origin)!=-1){
    	var HJMessage = e.data;
        if(isNotEmpty(HJMessage)){
        	//关闭iframe弹框
        	$("#windownbg").remove();
      	  	$("#windown-box").remove();
        	//打开创建稿件弹框
        	showMyModal('','create');
        	//解析数据填入稿件
        	window.localStorage.removeItem("HJMessage");
        	window.localStorage.setItem("HJMessage",HJMessage);
        }
    } else */
	if(CFBExternalUrl.indexOf(e.origin)!=-1){
    	var XTMessage = e.data;
    	var XTMessageObj = JSON.parse(XTMessage);
    	var callId = XTMessageObj.callId;
    	var iframeId =callId.split("_");
        if(cmedit.global.isNotEmpty(XTMessage)){
        	//关闭iframe弹框
        	$("#windownbg").remove();
      	  	$("#windown-box").remove();
    		//回填数据填入稿件
        	var son = window.top.document.getElementById('iframe_' + iframeId[1]).contentWindow;
			//.writeXTResourceData(XTMessage);
        	son.cmedit.EditSystem.writeXTResourceData(XTMessage);
        }
    }
    
},false));
//$(cmedit.RecycleSystem.init());
/*$(RecycleSystem.init());*/
